import React, { Component } from 'react';
import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import axios from "@iso/http";
import Card from "@iso/containers/UIElements/Card/Card.styles";
import Button from '@iso/components/uielements/button';

import Modals from '@iso/components/Feedback/Modal';

import ModalStyle, { ModalContent } from '@iso/containers/Feedback/Modal/Modal.styles';
import WithDirection from '@iso/lib/helpers/rtl';

import {Fieldset, Form, Label} from "@iso/containers/FirestoreCRUD/Article/Article.styles";
import Input, { Textarea } from '@iso/components/uielements/input';
import Qs from 'qs'

import {
    DateCell,
    ImageCell,
    LinkCell,
    TextCell,
} from '@iso/components/Tables/HelperCells';

import TableWrapper from "@iso/containers/Tables/AntTables/AntTables.styles";
import {Space,  Tree} from "antd";
import PopconfirmWrapper from "@iso/containers/Feedback/Popconfirm/Popconfirm.styles";
import Popconfirms from '@iso/components/Feedback/Popconfirm';
import {DownOutlined} from "@ant-design/icons";
import Tabs, { TabPane } from '@iso/components/uielements/tabs';
import PageHeader from '@iso/components/utility/pageHeader';
import {showErrorMessage,showSuccessMessage} from "@iso/containers/Feedback/Message/MessageUtils";
const isoModal = ModalStyle(Modals);
const Modal = WithDirection(isoModal);



const Popconfirm = (props) => (
    <PopconfirmWrapper>
        <Popconfirms {...props} />
    </PopconfirmWrapper>
);



export default class extends React.Component {


    constructor(props) {

        super(props);

        this.state={dataList:[],modalVisible:false,modalEditVisible:false,modalAuthoritySettingVisible:false,activateTabKey:1,menuTreeData:[],functionPointTreeData:[],menuCheckedKeys:[],functionPointCheckedKeys:[],menuHalfCheckedKeys:[],functionPointHalfCheckedKeys:[]};


    }


     renderCell = (object, type, key) => {
        const value = object[key];
        switch (type) {
            case 'ImageCell':
                return ImageCell(value);
            case 'DateCell':
                return DateCell(value);
            case 'LinkCell':
                return LinkCell(value);
            default:
                return TextCell(value);
        }
    };

    showAddModal=()=>{
        this.setState({modalVisible:true,name:'',code:'',category:'',description:''})
    };

    handleCancel = () => {
        this.setState({modalVisible:false})
    };

    showEditModal=(item)=>{
        let state={modalEditVisible:true, id:item.id, name:item.name,code:item.code,category:item.category,description: item.description};
        this.setState(state)
    };

    showAuthoritySettingModal=(item)=>{
        this.loadTreeData(item.id,'MENU')
        this.loadTreeData(item.id,'FUNCTION_POINT')
        this.setState({modalAuthoritySettingVisible:true,roleId:item.id})
    };

    handleEditCancel = () => {
        this.setState({modalEditVisible:false})
    };

    handleAuthoritySettingCancel = () => {
        this.setState({modalAuthoritySettingVisible:false})
    };

    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };
    loadData=(page)=>{
        axios.post('api/base/role/findByPage', Qs.stringify({
            page: page-1,
            size: 10
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let  dataList=data.data.content;

                let totalElements=data.data.totalElements;

                this.setState({dataList:dataList,totalElements:totalElements});
            })
            .catch(function (error) {
                console.log(error);
            });

    }


    add=() =>{
        let entity={name:this.state.name,code:this.state.code,category:this.state.category,description:this.state.description};
        axios.post('api/base/role/add', entity,{headers: {'Content-Type': 'application/json'}})
            .then((response)=>{
                let  data=response.data;
                if (response.status==200){
                    if(data.status==1){
                        this.setState({modalVisible:false})
                        this.loadData();
                        showSuccessMessage(data.message)
                    }else{
                        showErrorMessage(data.message);
                    }

                }else {

                    for (let i=0;i<data.errors.length;i++){

                        showErrorMessage(data.errors[i].defaultMessage);
                    }

                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }
    update=() =>{
        let entity={name:this.state.name,code:this.state.code,category:this.state.category,description:this.state.description,id:this.state.id};
        axios.post('api/base/role/update',entity,{headers: {'Content-Type': 'application/json'}})
            .then((response)=>{
                let  data=response.data;
                if (response.status==200){
                    if(data.status==1){
                        this.setState({modalEditVisible:false})
                        this.loadData();
                        showSuccessMessage(data.message)
                    }else{
                        showErrorMessage(data.message);
                    }

                }else {

                    for (let i=0;i<data.errors.length;i++){

                        showErrorMessage(data.errors[i].defaultMessage);
                    }

                }
            })
            .catch(function (error) {
                console.log(error);
            });

    }


    deleteById=(id)=> {

        axios.post('api/base/role/deleteById', Qs.stringify({
            id:id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.loadData(1);
                    showSuccessMessage(data.message)
                }else{
                    showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }


   componentDidMount() {
        this.loadData(1)
   }



    getColumns(){
        const columns = [ {
            title: 'ID',
            key: 'id',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'id'),
        },{
            title: '名称',
            key: 'name',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'name'),
        },{
            title: '代码',
            key: 'code',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'code'),
        },{
            title: '分类',
            key: 'category',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'category'),
        },{
            title: '备注',
            key: 'description',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'description'),
        },{
            title: '创建时间',
            key: 'createTime',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'createTime'),
        },{
            title: '操作',

            width: 100,
            render:(text,record) => (
            <Space size="middle">
                <Button
                    key="submit"
                    type="primary"
                    size="small"
                    onClick={()=>this.showEditModal(record)}
                >
                    编辑
                </Button>
                <Button
                    key="submit"
                    type="primary"
                    size="small"
                    onClick={()=>this.showAuthoritySettingModal(record)}
                >
                    权限设置
                </Button>

                <Popconfirm
                    title="确定要执行删除操作吗？"
                    okText="是"
                    cancelText="否"
                    onConfirm={()=>this.deleteById(record.id)}

                >
                    <Button
                        key="submit"
                        type="danger"
                        size="small"

                    >
                        删除
                    </Button>
                </Popconfirm>
            </Space>
            )
        }];

        const sortColumns = [
            { ...columns[0], sorter: false },
            { ...columns[1], sorter: false },
            { ...columns[2], sorter: false },
            { ...columns[3], sorter: false },
            { ...columns[4], sorter: false },
            { ...columns[5], sorter: false },
            { ...columns[6], sorter: false }
        ];
        return sortColumns;
    }

    getPagination(){
      let pagination= {
        showSizeChanger: true,//设置每页显示数据条数
        showQuickJumper: false,
        showTotal: () => `共${this.state.totalElements}条`,
        pageSize: 10,
          //数据的总的条数
        total: this.state.totalElements,
          //点击当前页码
        onChange: (current) => {this.loadData(current)},
          //设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        onShowSizeChange: (current, pageSize) => {
            console.log(pageSize);
            //this.onShowSizeChange(current, pageSize)
        }

     }
     return pagination;
    }

    tabActivateCallback=(key)=> {
        this.setState({activateTabKey:key})
    }


    getCheckedKeys=(checkedKeysList,list)=>{

        for(let i=0;i<list.length;i++){

            let item=list[i];
            //now we need to look at if this node has children
            //we only add checked keys when current node has no children and marked as checked==true
            //for if current node is marked as checked==true , our tree component will automatically checked all children of this current node,this may cause some problems
            //if we check some but not all children of current node, the current node will automatically marked as halfCheck

            if(item.children.length>0){
                checkedKeysList=this.getCheckedKeys(checkedKeysList,item.children)
            }else {
                if(item.checked==true){
                    checkedKeysList.push('resources_key_'+item.id);
                }
            }


        }
        return checkedKeysList;
    }


    loadTreeData=(roleId,resourcesType) =>{
        axios.post('api/base/resources/getCheckBoxTree', Qs.stringify({
            resourcesType:resourcesType,
            roleId:roleId
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let list=data.data


                let checkedKeyList=this.getCheckedKeys([],list);

                if(resourcesType=='MENU'){

                    this.setState({'menuTreeData':list,'menuCheckedKeys':checkedKeyList});

                }else {
                    this.setState({'functionPointTreeData':list,'functionPointCheckedKeys':checkedKeyList});
                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }


    menuTreeOnCheck= (checkedKeys, e) => {
        this.setState({menuCheckedKeys:checkedKeys,menuHalfCheckedKeys:e.halfCheckedKeys})
    }

    functionPointTreeOnCheck= (checkedKeys, e) => {
        this.setState({functionPointCheckedKeys:checkedKeys,functionPointHalfCheckedKeys:e.halfCheckedKeys})
    }

    getIdsFromKeys=(checkedKeys)=>{
        let ids=new Array();
        for(let i=0;i<checkedKeys.length;i++){
            let key=checkedKeys[i];
            let id=key.replaceAll('resources_key_','');
            ids.push(id);
        }
        return ids;
    }

    saveResourceRole=()=> {
        let resourcesType='';
        let resourcesIds=[];
        let checkedKeys=[];
        if(this.state.activateTabKey=='1'){
            resourcesType='MENU';
            checkedKeys=this.state.menuCheckedKeys.concat(this.state.menuHalfCheckedKeys);
        }else{
            resourcesType='FUNCTION_POINT';
            checkedKeys=this.state.functionPointCheckedKeys.concat(this.state.functionPointHalfCheckedKeys);
        }
        let ids=this.getIdsFromKeys(checkedKeys)
        resourcesIds=ids.join(',')
        axios.post('api/base/resourcesRole/update', Qs.stringify({
            roleId:this.state.roleId,
            resourcesType:resourcesType,
            resourcesIds:resourcesIds
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status===1){
                    this.setState({modalAuthoritySettingVisible:false})
                    showSuccessMessage(data.message)
                }else{
                    showErrorMessage(data.message);
                }
            })
            .catch(function (error) {
                console.log(error);
            });

    }


    render() {
    return (
      <LayoutContentWrapper style={{ height: '100vh' }}>
          <PageHeader>
              角色管理
          </PageHeader>
        <LayoutContent style={{ height: '100vh',overflow:'scroll' }}>

            <Modal
                visible={this.state.modalVisible}
                title="添加"
                onCancel={this.handleCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.add}
                    >
                        确定
                    </Button>,
                ]}
            >
                <Form>
                        <Fieldset>
                            <Label>名称:</Label>
                            <Input
                                label="名称"
                                placeholder="名称"
                                value={this.state.name}
                                onChange={e => this.onRecordChange(e, 'name')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>代码:</Label>
                            <Input
                                label="名称"
                                placeholder="请输入英文或英文与数字组合的代码"
                                value={this.state.code}
                                onChange={e => this.onRecordChange(e, 'code')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>分类:</Label>
                            <Input
                                label="分类"
                                placeholder="分类"
                                value={this.state.category}
                                onChange={e => this.onRecordChange(e, 'category')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>备注</Label>
                            <Textarea
                                label="备注"
                                placeholder="备注"
                                rows={5}
                                value={this.state.description}
                                onChange={e => this.onRecordChange(e, 'description')}
                            />
                        </Fieldset>
                    </Form>

            </Modal>


            <Modal
                visible={this.state.modalEditVisible}
                title="编辑"
                onCancel={this.handleEditCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleEditCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.update}
                    >
                        确定
                    </Button>,
                ]}
            >
                <Form >
                    <Fieldset>
                        <Label>名称:</Label>
                        <Input
                            label="名称"
                            placeholder="名称"
                            value={this.state.name}
                            onChange={e => this.onRecordChange(e, 'name')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>代码:</Label>
                        <Input
                            label="名称"
                            placeholder="请输入英文或英文与数字组合的代码"
                            value={this.state.code}
                            onChange={e => this.onRecordChange(e, 'code')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>分类:</Label>
                        <Input
                            label="分类"
                            placeholder="分类"
                            value={this.state.category}
                            onChange={e => this.onRecordChange(e, 'category')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>备注</Label>
                        <Textarea
                            label="备注"
                            placeholder="备注"
                            rows={5}
                            value={this.state.description}
                            onChange={e => this.onRecordChange(e, 'description')}
                        />
                    </Fieldset>
                </Form>

            </Modal>


            <Modal
                visible={this.state.modalAuthoritySettingVisible}
                title="权限设置"
                onCancel={this.handleAuthoritySettingCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleAuthoritySettingCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.saveResourceRole}

                    >
                        确定
                    </Button>,
                ]}

            >
                <Tabs defaultActiveKey="1" onChange={this.tabActivateCallback}>
                    <TabPane tab="菜单" key="1">
                        <Tree
                            checkable={true}
                            switcherIcon={<DownOutlined />}
                            checkedKeys={this.state.menuCheckedKeys}
                            onCheck={this.menuTreeOnCheck}

                            treeData={this.state.menuTreeData}
                        />

                    </TabPane>
                    <TabPane tab="功能" key="2">
                        <Tree
                            checkable={true}
                            switcherIcon={<DownOutlined />}
                            onCheck={this.functionPointTreeOnCheck}
                            checkedKeys={this.state.functionPointCheckedKeys}
                            treeData={this.state.functionPointTreeData}
                        />
                    </TabPane>

                </Tabs>

            </Modal>

            <Button
                key="submit"
                type="primary"
                size="small"
                onClick={()=>this.showAddModal()}
            >
                添加
            </Button>

            <Card
                title='角色管理'
                style={{ width: '100%' }}
            >


                <TableWrapper
                    columns={this.getColumns()}
                    dataSource={this.state.dataList}
                    className="isoSortingTable"
                    pagination={this.getPagination()}
                />



            </Card>

        </LayoutContent>
      </LayoutContentWrapper>
    );
  }
}
